import { BadRequestException, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from './entities/auth.entity';
import { Repository } from 'typeorm';
import * as bcrypt from 'bcryptjs';
import { JwtService } from '@nestjs/jwt';

@Injectable()
export class AuthService {
  constructor(
    @InjectRepository(User) private readonly user: Repository<User>,
    private readonly jwtService: JwtService,
  ) {}

  // 用户注册
  async signUp(params: User) {
    const findUser = await this.user.findOne({
      where: { username: params.username },
    });
    if (findUser && findUser.username === params.username) {
      return '用户已存在';
    }
    params.password = bcrypt.hashSync(params.password, 10);
    await this.user.save(params);
    return '注册成功';
  }

  // 用户登录
  async login(params: User) {
    const findUser = await this.user.findOne({
      where: { username: params.username },
    });

    // 未找到
    if (!findUser) return new BadRequestException('用户不存在');

    // 找到了
    const compareRes: boolean = bcrypt.compareSync(
      params.password,
      findUser.password,
    );
    if (!compareRes) return new BadRequestException('密码错误');
    const payload = {
      username: findUser.username,
    };
    console.log(params);
    return {
      access_token: this.jwtService.sign(payload),
      msg: '登录成功',
    };
  }
}
